<?php
namespace Org\WechatTest;

class WechatTest
{
	private $token;
	private $appid;
	private $appsecret;

	public function __construct($options)
	{
		$this->token = isset($options['token'])?$options['token']:'';
		$this->appid = isset($options['appid'])?$options['appid']:'';
		$this->appsecret = isset($options['appsecret'])?$options['appsecret']:'';
	}

	public function valid()
	{
		$echoStr = $_GET["echostr"];

		//valid signature , option
		if($this->checkSignature()){
			echo $echoStr;
			exit;
		}
	}

	public function responseMsg()
	{
		//get post data, May be due to the different environments
		$postStr = $GLOBALS["HTTP_RAW_POST_DATA"];
		//extract post data
		if (!empty($postStr)){
			/* libxml_disable_entity_loader is to prevent XML eXternal Entity Injection,
			   the best way is to check the validity of xml by yourself */
			libxml_disable_entity_loader(true);

			//微信传过来的xml解析
			$postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
			$fromUsername = $postObj->FromUserName;
			$toUsername = $postObj->ToUserName;
			$keyword = trim($postObj->Content);
			$msgType = $postObj->MsgType;
			$event = $postObj->Event;
			$eventKey = $postObj->EventKey;
			$time = time();

			$textTpl = $this->texttpl();
			if(!empty( $keyword ))
			{
				if($keyword == '图片'){
					$textpicTpl = $this->picturetpl();
					$msgType = "image";
					$mediaid = "NOp6cBVRaNSKy8cRmZAMbUyvsR0-UbbXgz0exKLRjYI";
					$resultStr = sprintf($textpicTpl, $fromUsername, $toUsername, $time, $msgType, $mediaid);
					//给微信传过去xml
					echo $resultStr;
				}elseif($keyword == '图文'){
					$textnewsTpl = $this->imagetxttpl();
					$msgType = "news";
					$picurl = 'http://mmbiz.qpic.cn/mmbiz/9vhD5XbU5uiaYOpOYOOEib1Tl6we6ZRoibcC0icibicaqic7SZ41QyjI0HO4B2Wp67steNNws5OLCpY39dhoJaFYJN29A/0?wx_fmt=jpeg';
					$url = 'http://www.baidu.com';
					$title = '你好';
					$des = '欢迎欢迎';
					$resultStr = sprintf($textnewsTpl, $fromUsername, $toUsername, $time, $msgType,2,$title,$des,$picurl,$url,$title,$des,$picurl,$url);
					//给微信传过去xml
					echo $resultStr;
				}
				else{
					$msgType = "text";
					$contentStr = "欢迎来到欣欣家哦";
					$resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
					//给微信传过去xml
					echo $resultStr;
				}
			}else{
				if($msgType == 'event' && $event == 'CLICK'){
					if($eventKey == 'good'){
						$msgType = "text";
						$contentStr = "哈哈，你是个好人^o^";
						$resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
						echo $resultStr;
					}elseif($eventKey == 'picture'){
						$textpicTpl = $this->picturetpl();
						$msgType = "image";
						$mediaid = "dRGWnLdTrP3aCAvKRezHkZuqCDwhDTEJdoLMIh6aFk4";
						$resultStr = sprintf($textpicTpl, $fromUsername, $toUsername, $time, $msgType, $mediaid);
						echo $resultStr;
					}elseif($eventKey == 'album'){
						$textnewsTpl = $this->imagetxttpl();
						$msgType = "news";
						$picurl = 'http://mmbiz.qpic.cn/mmbiz/9vhD5XbU5uiaD1Uo8IMicoEGWRjqgcmnfzV14e2AEukTzvyKDjcEZRgzGu0o2ia9VsOUHHPCI5IdqFaRO0Us2I9cw/0?wx_fmt=png';
//						$url = 'http://xinxin.oschina.mopaas.com/index.php/Home/Index/testpics';
						$url = 'http://user.qzone.qq.com/1011966923/4';
						$title1 = '你要点进去查看？';
						$title2 = '点进去看噢，哦啦啦~~*o*(其实偶qq空间更多，这秘密我不会告诉你的啦*o*)';
						$des = '点击进去查看噢，哦啦啦~~';

						$resultStr = sprintf($textnewsTpl, $fromUsername, $toUsername, $time, $msgType,2,$title1,$des,$picurl,$url,$title2,$des,$picurl,$url);
						//给微信传过去xml
						echo $resultStr;
					}

				}
				echo "Input something...";
			}

		}else {
			echo "";
			exit;
		}
	}

	public function checkSignature()
	{
		// you must define TOKEN by yourself
		if (!$this->token) {
			throw new Exception('TOKEN is not defined!');
		}

		$signature = $_GET["signature"];
		$timestamp = $_GET["timestamp"];
		$nonce = $_GET["nonce"];

		$token = $this->token;
		$tmpArr = array($token, $timestamp, $nonce);
		// use SORT_STRING rule
		sort($tmpArr, SORT_STRING);
		$tmpStr = implode( $tmpArr );
		$tmpStr = sha1( $tmpStr );

		if( $tmpStr == $signature ){
			return true;
		}else{
			return false;
		}
	}

	/*
	 * 获取access_token
	 */
	public function getaccesstoken(){
		//从缓存里取access_token
		session_start();
		if($_SESSION['access_token']){
			return $_SESSION['access_token'];
		}

		//获取access_token
		$appId = $this->appid;
		$appsecret = $this->appsecret;

		$tokenurl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$appId&secret=$appsecret";
		$tokenInfo = json_decode(curl_get($tokenurl));
		$access_token = $tokenInfo->access_token;
		$expires_in = $tokenInfo->expires_in;

		$_SESSION['access_token'] = $access_token;
		$this->start_session($expires_in);

		return $access_token;
	}

	/*
	 * 获取jsapi_ticket
	 */
	public function getticket(){
		//从缓存取
		if($_COOKIE['jsapi_tiket']){
			return $_COOKIE['jsapi_tiket'];
		}

		//获取access_token
		$access_token = $this->getaccesstoken();
		$url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=$access_token&type=jsapi";
		$info = json_decode($this->http_get($url));
		$ticket = $info->ticket;
		$expires_in = $info->expires_in;

		setcookie('jsapi_tiket',$ticket,time()+$expires_in);

		return $info->ticket;
	}

	/*
	 * 获取签名
	 */
	public function getSignPackage() {
		$jsapiTicket = $this->getticket();

		// 注意 URL 一定要动态获取，不能 hardcode.
		$protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
		$url = "$protocol$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";

		$timestamp = time();
		$nonceStr = $this->createNonceStr();

		// 这里参数的顺序要按照 key 值 ASCII 码升序排序
		$string = "jsapi_ticket=$jsapiTicket&noncestr=$nonceStr&timestamp=$timestamp&url=$url";

		$signature = sha1($string);
		$signPackage = array(
			"appId"     => $this->appid,
			"nonceStr"  => $nonceStr,
			"timestamp" => $timestamp,
			"url"       => $url,
			"signature" => $signature,
			"rawString" => $string
		);
		return $signPackage;
	}

	/*
	 * 获取ip_list
	 */
	public function getwxiplist(){
		$access_token = $this->getaccesstoken();
		$wxipurl = "https://api.weixin.qq.com/cgi-bin/getcallbackip?access_token=$access_token";
		$wxipInfo = json_decode(curl_get($wxipurl));
		return $wxipInfo->ip_list;
	}

	/**
	 * 创建自定义菜单
	 */
	public function createMenu(){
		//自定义按钮数据
		$data = array(
			'button' => array(
				0 => array(
					"type"     => "view",
					"name"     => "搜索",
					"url"      => "http://www.baidu.com/"
				),
				1 => array(
					"type"     => "view",
					"name"     => "视频",
					"url"      => "http://v.qq.com/"
				),
				2 => array(
					"name"     => "菜单",
					"sub_button" => array(
						0 => array(
							"type"     => "view",
							"name"     => "我的首页",
							"url"      => "http://xinxin.oschina.mopaas.com/index.php"
						),
						1 => array(
							"type" => "click",
                            "name" => "赞一下呗",
                            "key"  => "good",
						),
						2 => array(
							"type" => "click",
							"name" => "欣欣本尊",
							"key"  => "picture",
						),
						3 => array(
							"type" => "click",
							"name" => "她要嫁人啦",
							"key"  => "album",
						),

					)
				)

			)
		);

		$data = json_encode($data);
		//请求微信接口，创建
		$access_token = $this->getaccesstoken();
		$result = $this->http_post("https://api.weixin.qq.com/cgi-bin/menu/create?access_token=$access_token",$data);
		if ($result)
		{
			$json = json_decode($result,true);
			if (!$json || !empty($json['errcode'])) {
				$this->errCode = $json['errcode'];
				$this->errMsg = $json['errmsg'];
				return false;
			}
			return true;
		}
		return false;
	}

	/*
	 *  新增临时素材
	 *   $media = array(
	 *		'media' => '@C:\Users\Administrator\Desktop\3.jpg'
	 *	);
	 *  @param array $media
	 */
	public function mediaupload($media){
		$access_token = $this->getaccesstoken();
		$type = 'image';

		$result = $this->http_post("https://api.weixin.qq.com/cgi-bin/material/add_material?access_token=$access_token&type=$type",$media,true);
		return json_decode($result);
	}

	/*
	 * 获取临时素材
	 */
	public function getmedia(){
		$access_token = $this->getaccesstoken();

		$data = array(
			'type' => 'image',
			'offset' => 0,
			'count' => 20,
		);
		$data = json_encode($data);

		$result = $this->http_post("https://api.weixin.qq.com/cgi-bin/material/batchget_material?access_token=$access_token",$data);
		return json_decode($result);
	}

	/*
	 * 微信授权
	 */
	public function wxauth($state,$redirect_url,$siteurl){
		$appid = $this->appid;
		$scope = 'snsapi_userinfo';
//		$redirect_url = $siteurl.'/index.php/Home/Wechat/wechatauth'.'?passurl='.$redirect_url;
		$redirect_url = $siteurl.'/index.php/Home/Wechat/wechatauth';
		$redirect_url = urlencode($redirect_url);
		$url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=$appid&redirect_uri=$redirect_url&response_type=code&scope=$scope&state=$state#wechat_redirect";
		header("Location: $url");
	}

	/*
	 * 是否在微信内
	 */
	public function inwechat(){
		$pos = stripos($_SERVER['HTTP_USER_AGENT'], 'MicroMessenger');
		if (false !== $pos) {
			return true;
		}
		return false;
	}

	/*
	 * 获取微信用户列表(返回openid数组)
	 */
	public function getwxuserlist(){
		$access_token = $this->getaccesstoken();
		$next_openid = '';
		$url = "https://api.weixin.qq.com/cgi-bin/user/get?access_token=$access_token&next_openid=$next_openid";
		$info = json_decode(curl_get($url));
		return $info->data->openid;
	}

	/*
	 * 获取用户基本信息
	 */
	public function getwxuserinfo($openid){
		$access_token = $this->getaccesstoken();
		$url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=$access_token&openid=$openid&lang=zh_CN";
		$info = json_decode(curl_get($url));
		if($info->errorcode > 0){
			return false;
		}
		return $info;
	}

	/*
	 * 生成随机字符串
	 */
	private function createNonceStr($length = 16) {
		$chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
		$str = "";
		for ($i = 0; $i < $length; $i++) {
			$str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
		}
		return $str;
	}

	/**
	 * POST 请求
	 * @param string $url                     //url链接
	 * @param array $param                    //参数
	 * @param boolean $post_file              //是否文件上传
	 * @return string content
	 */
	private function http_post($url,$param,$post_file=false){
		$oCurl = curl_init();
		if(stripos($url,"https://")!==FALSE){
			curl_setopt($oCurl, CURLOPT_SSL_VERIFYPEER, FALSE);
			curl_setopt($oCurl, CURLOPT_SSL_VERIFYHOST, false);
			curl_setopt($oCurl, CURLOPT_SSLVERSION, 1); //CURL_SSLVERSION_TLSv1
		}
		if (is_string($param) || $post_file) {
			$strPOST = $param;
		} else {
			$aPOST = array();
			foreach($param as $key=>$val){
				$aPOST[] = $key."=".urlencode($val);
			}
			$strPOST =  join("&", $aPOST);
		}
		curl_setopt($oCurl, CURLOPT_URL, $url);
		curl_setopt($oCurl, CURLOPT_RETURNTRANSFER, 1 );
		curl_setopt($oCurl, CURLOPT_POST,true);
		curl_setopt($oCurl, CURLOPT_POSTFIELDS,$strPOST);
		$sContent = curl_exec($oCurl);
		$aStatus = curl_getinfo($oCurl);
		curl_close($oCurl);
		if(intval($aStatus["http_code"])==200){
			return $sContent;
		}else{
			return false;
		}
	}

	/**
	 * GET 请求
	 *
	 * @param $url
	 * @return bool|mixed
	 */
	private function http_get($url)
	{
		$oCurl = curl_init();
		if (stripos($url, "https://") !== FALSE) {
			curl_setopt($oCurl, CURLOPT_SSL_VERIFYPEER, FALSE);
			curl_setopt($oCurl, CURLOPT_SSL_VERIFYHOST, FALSE);
		}

		curl_setopt($oCurl, CURLOPT_TIMEOUT, 6);
		curl_setopt($oCurl, CURLOPT_URL, $url);
		curl_setopt($oCurl, CURLOPT_RETURNTRANSFER, 1);
		$sContent = curl_exec($oCurl);
		$aStatus = curl_getinfo($oCurl);
		curl_close($oCurl);
		if (intval($aStatus["http_code"]) == 200) {
			return $sContent;
		} else {
			return false;
		}
	}

	/*
	 * 回复图片消息模板
	 */
	private function picturetpl(){
		$textpicTpl = "<xml>
					<ToUserName><![CDATA[%s]]></ToUserName>
					<FromUserName><![CDATA[%s]]></FromUserName>
					<CreateTime>%s</CreateTime>
					<MsgType><![CDATA[%s]]></MsgType>
					<Image>
					<MediaId><![CDATA[%s]]></MediaId>
					</Image>
					</xml>";
		return $textpicTpl;
    }

	/*
	 * 图文消息回复模板
	 */
	private function imagetxttpl(){
		$textnewsTpl = "<xml>
						<ToUserName><![CDATA[%s]]></ToUserName>
						<FromUserName><![CDATA[%s]]></FromUserName>
						<CreateTime>%s</CreateTime>
						<MsgType><![CDATA[%s]]></MsgType>
						<ArticleCount>%s</ArticleCount>
						<Articles>
						<item>
						<Title><![CDATA[%s]]></Title>
						<Description><![CDATA[%s]]></Description>
						<PicUrl><![CDATA[%s]]></PicUrl>
						<Url><![CDATA[%s]]></Url>
						</item>
						<item>
						<Title><![CDATA[%s]]></Title>
						<Description><![CDATA[%s]]></Description>
						<PicUrl><![CDATA[%s]]></PicUrl>
						<Url><![CDATA[%s]]></Url>
						</item>
						</Articles>
					    </xml>";
		return $textnewsTpl;
	}

	/*
	 * 文字消息回复模板
	 */
	private function texttpl(){
		$textTpl = "<xml>
					<ToUserName><![CDATA[%s]]></ToUserName>
					<FromUserName><![CDATA[%s]]></FromUserName>
					<CreateTime>%s</CreateTime>
					<MsgType><![CDATA[%s]]></MsgType>
					<Content><![CDATA[%s]]></Content>
					<FuncFlag>0</FuncFlag>
					</xml>";
		return $textTpl;
	}

	/*
	 * 设置session缓存时间
	 */
	private function start_session($expire=0){
	   if($expire==0){
		   $expire=ini_get('session.gc_maxlifetime');
	   }else{
		   ini_set('session.gc_maxlifetime',$expire);
	   }
	   if(empty($_COOKIE['PHPSESSID'])){
		   session_set_cookie_params($expire);
	       session_start();
	   }else{
			session_start();
	        setcookie('PHPSESSID',session_id(),time()+$expire);
	   }
	}

}